package com.jiguang.shangcheng.servlet;

import com.jiguang.shangcheng.dao.AdminDao;
import com.jiguang.shangcheng.dao.ShangChengDao;
import com.jiguang.shangcheng.pojo.Order;
import com.jiguang.shangcheng.pojo.Product;
import com.jiguang.shangcheng.pojo.User;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/shang/shang_buyProduct")
public class buyProduct extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置字符集
        resp.setContentType("text/html;charset=utf-8");
        req.setCharacterEncoding("UTF-8");
        //获取参数
        String id = req.getParameter("id");

        //判断用户是否实名以及是否填写卡号
        HttpSession session = req.getSession();
        User user= (User) session.getAttribute("name");

        if(user.getBankCard() == null || user.getTurename() == null || user.getBankCard().equals("") || user.getTurename().equals("")){
            //购买失败
            PrintWriter out = resp.getWriter();
            out.println("<script> alert('购买失败,请先完善信息');location.href='/shang/shang_person.jsp';</script>");
            out.close();
            return;
        }else{
            //判断商品是主人是否是自己
            AdminDao adminDao = new AdminDao();
            Product product = adminDao.selectProductByid(Integer.parseInt(id));
            if(product.getUserId().equals(user.getId())){
                PrintWriter out = resp.getWriter();
                out.println("<script> alert('您是该商品的主人，无需购买');location.href='/shang/shang_index';</script>");
                out.close();
                return;
            }

            //生成订单
            Order order = new Order();
            order.setUserId(user.getId());
            order.setProductId(Integer.parseInt(id));
            ShangChengDao shangChengDao = new ShangChengDao();
            boolean result =  shangChengDao.insertOrder(order);
            if(result){
                //购买失败
                PrintWriter out = resp.getWriter();
                out.println("<script>alert('订单已生成,待卖家确认');location.href='/shang/shang_index';</script>");
                out.close();
            }else{
                //购买失败
                PrintWriter out = resp.getWriter();
                out.println("<script>alert('购买失败');location.href='/shang/shang_index';</script>");
                out.close();
            }
        }
    }
}
